<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-5-25
 * Time: 下午4:47
 */

namespace common\components\gps;


use common\components\tools\Tools;
use common\models\CarGpsOrder;
use yii\base\ErrorException;
use yii\httpclient\Client;
use yii\log\FileTarget;

class Sunmu extends Gps implements Api
{
    const PRE_SIGN = '802';
    const NAME = 'sunmu';
    const NOTE = '隼目';

    public function addGps()
    {
        /*$_data = [
            'client_name' => "",
            'plate_number' => "",
            'custom_name' => "",
        ];*/
        $this->checkOrder();
        $order = $this->order;
        $_data = unserialize($order->data);
        if (!$_data['client_name']){
            throw new ErrorException("没有找到组织名", 1024);
        }
        /*if (!$_data['plate_number']){
            throw new ErrorException("没有找到车牌号", 1025);
        }*/
        if (!$_data['custom_name']){
            throw new ErrorException("没有找到客户名", 1026);
        }
        $_x = [
            'clientName' => $_data['client_name'],
            'userName' => $_data['client_name'],
            'loginName' => $_data['client_name'],
            'loginPwd' => '888888',
        ];
        $this->addUser($_x);
        $_config = ['baseUrl' => Config::$sunmu['url'].Config::$sunmu['add_gps_uri']];
        $__data = [
            'clientName' => $_data['client_name'],
            'vehicleId' => $order->guarantee_company_car_id,
            'vehicleNo' => $_data['plate_number'],
            'customerName' => $_data['custom_name'],
            'gprsCode' => $order->gps_serial_number,
            'sign' => md5($order->gps_serial_number.Config::$sunmu['connent_key']),
        ];
        $client = new Client();
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($_config['baseUrl'])
            ->setData($__data)
            ->send();
        $x = json_decode($response->content);
        if (!isset($x->success)){
            throw new ErrorException($x->msg, 1030);
        }
        $_x = Tools::objectToArray(json_decode($response->content));
        return [
            'platform_back' => $response->content,
            '_back' => Tools::objectToArray(json_decode($response->content)),
            'other_data' => [
                'success' => $_x['success'],
                'msg' => $_x['msg'],
            ],
        ];
    }

    public function getGps()
    {
        $this->checkOrder();
        $order = $this->order;
        if (isset($order->other_data['o_add_time'])){}else{
            \Yii::$app->response->statusCode = 402;
            return [
                'msg' => "隼木需要other_data有o_add_time",
            ];
        }
        $_config = ['baseUrl' => Config::$sunmu['url'].Config::$sunmu['get_gps_data_uri']];
        $__data = [
            'gprsCode' => $order->gps_serial_number,
            'sign' => md5($order->gps_serial_number.Config::$sunmu['connent_key']),
        ];
        $client = new Client();
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($_config['baseUrl'])
            ->setData($__data)
            ->send();
        /*$x = $client->createRequest()
            ->setMethod('get')
            ->setUrl($_config['baseUrl'])
            ->setData($__data)->fullUrl;
        foreach ($__data as $k => $v){
            $params[] = $k."=".$v;
        }
        $x = $x."?".Tools::arr2str($params, "&");
        var_dump($x);exit;*/
        if (isset($response->content)){
            $x = json_decode($response->content);
            $x = Tools::objectToArray($x);
            if (isset($x['gpstime'])&&isset($x['updatetime'])){
                $other_data = [
                    'r_gpstime_stamp' => substr($x['gpstime'], 0, 10),
                    'r_updatetime_stamp' => substr($x['updatetime'], 0, 10),
                    'r_gpstime' => date("Y-m-d H:i:s", substr($x['gpstime'], 0, 10)),
                    'r_updatetime' => date("Y-m-d H:i:s", substr($x['updatetime'], 0, 10)),
                    'r_gpsdate' => date("Y-m-d", substr($x['gpstime'], 0, 10)),
                    'r_updatedate' => date("Y-m-d", substr($x['updatetime'], 0, 10)),
                    'is_direct' => $order->isNewRecord,
                ];
                $t1 = $other_data['r_updatetime_stamp'];
                $t2 =  $other_data['r_updatetime_stamp'];
                if($t1 > $order->other_data['o_add_time'] && $t2 > $order->other_data['o_add_time']){
                    $other_data['gps_status'] = '已上线';
                    $other_data['gps_online_time'] = $other_data['r_updatetime_stamp'];
                }else{
                    $other_data['gps_status'] = '未上线';
                    $other_data['gps_online_time'] = $other_data['r_updatetime_stamp'];
                }
            }else{
                $other_data = [
                    'gps_status' => '未上线',
                ];
            }
        }else{
            $other_data = [
                'gps_status' => '未上线',
            ];
        }
        return [
            'platform_back' => $response->content,
            'order' => $order,
            'other_data' => $other_data,
        ];
    }

    public function addUser($data)
    {
        $data['sign'] = md5($data['loginName'].Config::$sunmu['connent_key']);
        $_config = ['baseUrl' => Config::$sunmu['url'].Config::$sunmu['add_user_uri']];
        $client = new Client();
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($_config['baseUrl'])
            ->setData($data)
            ->send();
//        $ft = new FileTarget();
//        $ft->logFile = \Yii::$app->getRuntimePath()."/logs/sunmu.log";
//        $ft->messages[] = [$data, 1, 'request', time()];
//        $ft->messages[] = [$response, 1, 'respone', time()];
//        $ft->export();
        return $response->content;
    }

    public function getGpsLocationData()
    {
        $this->checkOrder();
        $order = $this->order;
        $other_data = $order->other_data;
        if (isset($other_data['loginName'])){}else{
            return [
                'msg' => "隼木需要other_data有loginName",
            ];
        }
        $sign = md5( $order->other_data['loginName']. $order->gps_serial_number.Config::$sunmu['connent_key']);
        $order->other_data['loginName'] = urlencode($order->other_data['loginName']);
        $data = [];
        $data['url'] = Config::$sunmu['url'].'vehicle_client/monitor/position.html?loginName='.$order->other_data['loginName'].'&gprsCode='.$order->gps_serial_number.'&sign='.$sign;
        $data['html'] = '<script type="text/javascript">location.href = "'.$data['url'].'";</script>';
        return $data;
    }
}